package com.eric.gateway.sentinel;

import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * @ClassName SentinelExceptionHandler
 * @Description TODO
 * @Author Eric
 * @Date 2021/12/28 11:08
 * @Version 1.0
 */
@Slf4j
public class SentinelExceptionHandler implements UrlBlockHandler {


    @Override
    public void blocked(javax.servlet.http.HttpServletRequest httpServletRequest,
                        javax.servlet.http.HttpServletResponse httpServletResponse,
                        BlockException e) throws IOException {
        log.info("SentinelExceptionHandler >>>>  11 ");
        // BlockException 异常接口，其子类为Sentinel五种规则异常的实现类
        // AuthorityException 授权异常
        // DegradeException 降级异常
        // FlowException 限流异常
        // ParamFlowException 参数限流异常
        // SystemBlockException 系统负载异常
        SentinelResp data = new SentinelResp();
        if (e instanceof FlowException) {
            data = new SentinelResp(-1, "接口被限流了。");
        } else if (e instanceof DegradeException) {
            data = new SentinelResp(-2, "接口被降级了。");
        }

        log.info("SentinelExceptionHandler >>>>  22 ");
        httpServletResponse.setContentType("application/json;charset=utf-8");
        httpServletResponse.getWriter().write(JSON.toJSONString(data));
    }
}
